<template>
  <div class="attendance-container">
    <!-- 使用ElementUI的下拉框 -->
    <div class="select-month">
      <label>当前月份：</label>
      <el-select v-model="selectedMonth" placeholder="选择月份" @change="fetchDataByMonth">
        <el-option
          v-for="month in availableMonths"
          :key="month"
          :label="month"
          :value="month"
        >
        </el-option>
      </el-select>
    </div>
    <!-- 新增卡片区域标题 -->
    <div class="section-title">
      <h2>本月考勤状态次数</h2>
    </div>

    <div class="card-container">
      <div
        class="card"
        v-for="(count, status) in statusCounts"
        :key="status"
        :style="{ backgroundColor: getCardColor(status) }"
      >
        <h2>{{ getStatusText(status) }}</h2>
        <p style="font-size: 20px">{{ count }} 次</p>
      </div>
      <!-- 新增本月请假次数卡片 -->
      <div
        class="card"
        :style="{ backgroundColor: themeColor.leave }"
      >
        <h2>本月请假次数</h2>
        <p style="font-size: 20px">{{ leaveCount }} 次</p>
      </div>
    </div>

    <div id="chart1" class="chart"></div>
    <div id="chart2" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getSignStatistic } from "@/api/attendance/signRecord";
import { listLeaveRecord } from "@/api/leave/leaveRecord";

export default {
  data() {
    return {
      loading: true,
      queryParams: {},
      statusCounts: { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0 },
      signData: [],
      dateSet: [],
      statusData: { 0: [], 1: [], 2: [], 3: [], 4: [] },
      themeColor: {
        primary: '#409eff',    // 准时签退
        success: '#67c23a',   // 准时签到
        warning: '#e6a23c',   // 迟到
        danger: '#f56c6c',    // 早退
        abnormal: '#7265e6',  // 考勤异常
        textColor: '#303133',
        subTextColor: '#606266',
        leave: '#ad13fa',
      },
      resizeTimer: null,
      leaveRecordList: [],
      leaveCount: 0,
      availableMonths: [],
      selectedMonth: '',
    };
  },
  mounted() {
    this.fetchAllData();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.resizeCharts);
  },
  methods: {
    getCardColor(status) {
      return [
        this.themeColor.success,    // 0
        this.themeColor.primary,    // 1
        this.themeColor.warning,    // 2
        this.themeColor.danger,     // 3
        this.themeColor.abnormal     // 4
      ][status];
    },

    async fetchAllData() {
      try {
        this.loading = true;
        const response = await getSignStatistic(this.queryParams);
        this.signData = response.data || [];
        const leaveResponse = await listLeaveRecord(this.queryParams);
        this.leaveRecordList = leaveResponse.rows;

        this.extractAvailableMonths();
        this.selectedMonth = this.getCurrentMonth();

        this.fetchDataByMonth();
      } catch (error) {
        console.error('获取数据失败', error);
        this.$message.error('数据加载失败，请重试');
      }
    },

    extractAvailableMonths() {
      const months = new Set();
      this.signData.forEach(item => {
        const date = new Date(item.signTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        months.add(`${year}-${month}`);
      });
      this.availableMonths = Array.from(months).sort();
    },

    getCurrentMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },

    async fetchDataByMonth() {
      const [year, month] = this.selectedMonth.split('-');
      const startDate = new Date(year, month - 1, 1);
      const endDate = new Date(year, month, 0);

      const filteredSignData = this.signData.filter(item => {
        const signDate = new Date(item.signTime);
        return signDate >= startDate && signDate <= endDate;
      });

      const filteredLeaveRecordList = this.leaveRecordList.filter(item => {
        const leaveDate = new Date(item.startTime);
        return leaveDate >= startDate && leaveDate <= endDate && item.approvalStatus ===1;
      });

      this.leaveCount = filteredLeaveRecordList.length;

      this.processData(filteredSignData);
      this.initCharts();
    },

    processData(signData) {
      Object.keys(this.statusCounts).forEach(key => this.statusCounts[key] = 0);

      signData.forEach(item => {
        const status = String(item.signStatus);
        if (status in this.statusCounts) {
          this.statusCounts[status]++;
        }
      });

      // 提取所有日期并按升序排序（关键修改）
      const allDates = signData.map(item => item.signTime.split(' ')[0]);
      this.dateSet = Array.from(new Set(allDates)).sort((a, b) => new Date(a) - new Date(b));

      this.statusData = {0: [], 1: [], 2: [], 3: [], 4: []};

      this.dateSet.forEach((date, index) => {
        [0, 1, 2, 3, 4].forEach(s => this.statusData[s][index] = 0);
        signData.filter(item => item.signTime.split(' ')[0] === date).forEach(item => {
          const status = item.signStatus;
          this.statusData[status][index]++;
        });
      });
    },

    initCharts() {
      // 柱状图配置
      const chart1 = echarts.getInstanceByDom(document.getElementById('chart1')) || echarts.init(document.getElementById('chart1'));
      chart1.setOption({
        color: [
          this.themeColor.success,
          this.themeColor.primary,
          this.themeColor.warning,
          this.themeColor.danger,
          this.themeColor.abnormal
        ],
        title: {
          text: '每日考勤状态分布',
          textStyle: {
            fontSize: 18,
            fontWeight: 600,
            color: this.themeColor.textColor
          },
          left: 'left',
          top: '5%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          formatter: (params) => {
            let html = `<div style="padding: 12px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1)">`;
            html += `<div style="font-size: 14px; font-weight: 500; color: #303133;">${params[0].name}</div>`;
            params.forEach(item => {
              html += `<div style="display: flex; align-items: center; gap: 6px; margin: 8px 0;">
                        <div style="width: 10px; height: 10px; background: ${item.color}; border-radius: 2px;"></div>
                        <span style="color: #606266;">${item.seriesName}: ${item.value} 次</span>
                      </div>`;
            });
            return html + '</div>';
          }
        },
        grid: {top: '20%', left: '3%', right: '3%', bottom: '15%'},
        xAxis: {
          type: 'category',
          data: this.dateSet,
          axisTick: {alignWithLabel: true},
          axisLine: {color: '#e4e7ed'},
          axisLabel: {
            color: this.themeColor.subTextColor,
            fontSize: 12,
            margin: 8
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {type: 'dashed', color: '#f0f2f5'}
          },
          axisLine: {color: '#e4e7ed'},
          axisLabel: {
            color: this.themeColor.subTextColor,
            fontSize: 12
          }
        },
        series: this.getBarSeriesData()
      });

      // 饼图配置
      const chart2 = echarts.getInstanceByDom(document.getElementById('chart2')) || echarts.init(document.getElementById('chart2'));
      chart2.setOption({
        color: [
          this.themeColor.success,
          this.themeColor.primary,
          this.themeColor.warning,
          this.themeColor.danger,
          this.themeColor.abnormal
        ],
        title: {
          text: '本月考勤状态占比',
          textStyle: {
            fontSize: 18,
            fontWeight: 600,
            color: this.themeColor.textColor
          },
          left: 'left',
          top: '5%'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          left: '10%',
          top: '20%',
          bottom: '20%',
          data: Object.keys(this.statusCounts).map(status => this.getStatusText(status)),
          textStyle: {color: this.themeColor.subTextColor, fontSize: 20, fontWeight: '500'},
          itemWidth: 18,
          itemHeight: 18,
          gap: 12
        },
        series: this.getPieSeriesData()
      });
    },

    getBarSeriesData() {
      return [
        {name: '准时签到', type: 'bar', stack: 'status', data: this.statusData[0], ...this.getBarItemStyle(0)},
        {name: '准时签退', type: 'bar', stack: 'status', data: this.statusData[1], ...this.getBarItemStyle(1)},
        {name: '迟到', type: 'bar', stack: 'status', data: this.statusData[2], ...this.getBarItemStyle(2)},
        {name: '早退', type: 'bar', stack: 'status', data: this.statusData[3], ...this.getBarItemStyle(3)},
        {name: '考勤异常', type: 'bar', stack: 'status', data: this.statusData[4], ...this.getBarItemStyle(4)}
      ];
    },

    getBarItemStyle(index) {
      return {
        barWidth: '18%',
        itemStyle: {
          borderRadius: 6,
          shadowBlur: 8,
          shadowColor: 'rgba(0,0,0,0.08)',
          shadowOffsetX: 2,
          shadowOffsetY: 2,
          color: [
            this.themeColor.success,
            this.themeColor.primary,
            this.themeColor.warning,
            this.themeColor.danger,
            this.themeColor.abnormal
          ][index]
        }
      };
    },

    getPieSeriesData() {
      return [{
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '50%'],
        itemStyle: {
          borderRadius: 8,
          borderWidth: 2,
          borderColor: '#fff',
          shadowBlur: 10,
          shadowColor: 'rgba(0,0,0,0.1)'
        },
        label: {
          show: true,
          formatter: (params) => {
            return `{name|${params.name}}\n{value|${params.percent.toFixed(1)}%}`;
          },
          rich: {
            name: {
              fontSize: 14,
              fontWeight: '500',
              color: this.themeColor.textColor,
              lineHeight: 24
            },
            value: {
              fontSize: 12,
              color: this.themeColor.subTextColor,
              lineHeight: 20
            }
          }
        },
        labelLine: {
          length: 20,
          length2: 10,
          lineStyle: {
            color: '#e4e7ed',
            type: 'solid'
          }
        },
        data: Object.entries(this.statusCounts).map(([status, count]) => ({
          value: count,
          name: this.getStatusText(status)
        }))
      }];
    },

    getStatusText(status) {
      return {
        '0': '准时签到',
        '1': '准时签退',
        '2': '迟到',
        '3': '早退',
        '4': '考勤异常'
      }[status] || '未知';
    },

    resizeCharts() {
      if (this.resizeTimer) clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        const chart1 = echarts.getInstanceByDom(document.getElementById('chart1'));
        const chart2 = echarts.getInstanceByDom(document.getElementById('chart2'));
        chart1?.resize();
        chart2?.resize();
      }, 100);
    }
  }
};
</script>

<style scoped>
.attendance-container {
  padding: 20px 24px 15px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.select-month {
  margin-bottom: 20px;
}

.section-title {
  position: relative;
  margin-bottom: 25px;
}

.section-title h2 {
  font-size: 18px !important;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  padding-left: 0;
}

.card-container {
  display: flex;
  flex-wrap: nowrap;
  gap: 24px;
  margin-bottom: 5px;
  overflow-x: auto;
  padding: 18px;
  background: #f8f9fa;
  border-radius: 12px;
}

.card {
  /* 修改flex-basis以适应6个卡片 */
  flex: 0 0 calc(16.666% - 20px);
  min-width: 150px;
  padding: 24px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  color: white;
  text-align: center;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.card:hover {
  transform: scale(1.03);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
}

.card h3 {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.card p {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
}

.chart {
  height: 470px;
  border-radius: 16px;
  margin-bottom: 5px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  background-color: #fff;
}

/* 清除ECharts默认标题样式 */
.echarts-title {
  left: 24px !important;
  text-align: left !important;
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #303133 !important;
}
</style>
